/*
 * not type checking this file because flow doesn't play well with
 * dynamically accessing methods on Array prototype
 */

import { def } from '../util/index'

const arrayProto = Array.prototype
// arrayMethod的隐式原型：__proto__, 指向Array.prototype
export const arrayMethods = Object.create(arrayProto)

const methodsToPatch = [
  'push',
  'pop',
  'shift',
  'unshift',
  'splice',
  'sort',
  'reverse'
]

/**
 * Intercept mutating methods and emit events
 */
methodsToPatch.forEach(function (method) {
  // cache original method
  const original = arrayProto[method]
  // 重写数组的"push,pop,shift,unshift,splice,sort,reverse"这7个方法
  def(arrayMethods, method, function mutator (...args) {
    // apply，调用数组原来的方法
    const result = original.apply(this, args)
    // this就是我们的数组对象target，this.__ob__就是其Observer实例对象。
    const ob = this.__ob__
    let inserted
    switch (method) {
      case 'push':
        // push、unshift一样，关于switch语句的用法，可以参考https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/switch
      // eslint-disable-next-line no-fallthrough
      case 'unshift':
        // unshift，添加到数组头部
        inserted = args;
        break
      case 'splice':
        // splice(start,deletCount, item1,item2),从第二个开始，是要添加的数据
        inserted = args.slice(2)
        break
    }
    // 如果inserted有数据，则对新添加进来的数据进行观察
    if (inserted) ob.observeArray(inserted)
    // notify change，重新渲染
    ob.dep.notify();
    // result：原生数组执行后的返回值
    return result
  })
})
